package dao;

import pojo.Student;
import utils.JDBCUtils;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

//和用户相关的数据层（操作数据库）
public class StudentDao {

    //根据账号，密码查询是否正常的操作
    public boolean loginQuery(String account,String password){
        String sql = "select * from student where name=? and password=?";
        ResultSet query = JDBCUtils.query(sql, account, password);
        boolean flag = false;
        try {
            if (query.next()){
                flag = true;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return flag;
    }
//添加学生信息
    public void saveStudent(Student student) {
        String sql = "insert into student(id,name,password,sex,major,age) values(?,?,?,?,?,?)";
        PreparedStatement pstmt = null;
        try {
            pstmt = JDBCUtils.getconnection().prepareStatement(sql);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        try {
            pstmt.setString(1,student.getId());
            pstmt.setString(2,student.getName());
            pstmt.setString(3,student.getPassword());
            pstmt.setString(4,student.getSex());
            pstmt.setString(5,student.getMajor());
            pstmt.setInt(6,student.getAge());
            pstmt.executeUpdate();

        } catch (SQLException e) {

            e.printStackTrace();
        }finally {
            JDBCUtils.free();
        }
    }
    //显示所有学生信息
    public List<Student> findAllStudents(){
        List<Student> stuList = new ArrayList<Student>();
        String sql = "select * from student";
        PreparedStatement pstmt = null;
        try {
            pstmt = JDBCUtils.getconnection().prepareStatement(sql);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            ResultSet rs = pstmt.executeQuery();
            while(rs.next()) {
                String id = rs.getString("id");
                String name = rs.getString("name");
                String password = rs.getString("password");
                String sex = rs.getString("sex");
                String major = rs.getString("major");
                int age = rs.getInt("age");
                Student stu = new Student(id,name,password,sex,major,age);
                stuList.add(stu);
            }
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.free();
        }
        return stuList;
    }
}

